<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="van-field 组件数值类型限制最大值的使用及思考">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2020-07-10-the-use-and-thinking-of-the-maximum-value-of-the-value-type-limit-of-the-van-field-component/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/vue/2530160-b3ba93c227f3c938.webp">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/vue/2530160-692c5182fcab0a4c.webp">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/vue/2530160-9374db8a64d9a137.webp">
  <meta property="article:published_time" content="2020-07-10T06:03:27.000Z">
  <meta property="article:modified_time" content="2020-07-10T06:03:27.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="Vue">
  <meta property="article:tag" content="van-field">
  <meta property="article:tag" content="组件">
  <meta property="article:tag" content="最大值">
  <meta property="article:tag" content="自定义组件">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2020-07-10-the-use-and-thinking-of-the-maximum-value-of-the-value-type-limit-of-the-van-field-component/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>van-field 组件数值类型限制最大值的使用及思考 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8B%E4%BB%B6%E4%BC%A0%E9%80%92%E6%B3%95"><span class="nav-number">1.</span> <span class="nav-text">事件传递法</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%A7%A3%E8%80%A6%E4%BA%8B%E4%BB%B6%E6%B3%95"><span class="nav-number">2.</span> <span class="nav-text">解耦事件法</span></a></li>
                  <li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%AE%8C%E6%95%B4%E4%BB%A3%E7%A0%81"><span class="nav-number">3.</span> <span class="nav-text">完整代码</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2020-07-10-the-use-and-thinking-of-the-maximum-value-of-the-value-type-limit-of-the-van-field-component/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              van-field 组件数值类型限制最大值的使用及思考
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2020-07-10 14:03:27" itemprop="dateCreated datePublished" datetime="2020-07-10T14:03:27+08:00">2020-07-10</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/Vue/" itemprop="url" rel="index"><span itemprop="name">Vue</span></a>
                  </span>
                </span>


                <span id="/blob/2020-07-10-the-use-and-thinking-of-the-maximum-value-of-the-value-type-limit-of-the-van-field-component/" class="post-meta-item leancloud_visitors" data-flag-title="van-field 组件数值类型限制最大值的使用及思考" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io/" alt="总访客数量"></a></p>
            <blockquote>
              <p>在使用<code>Vant</code>组件 <code>van-field</code>时需要限制数值类型的最大值，尝试了两种方法，最终确定了一种最优方案</p>
            </blockquote>
            <blockquote>
              <p>版本说明 <code>&quot;vue&quot;: &quot;^2.6.8&quot;</code> <code> &quot;vant&quot;: &quot;^2.9.0&quot;</code></p>
            </blockquote>
            <p>因为在组件<code>van-field</code>外面有嵌套了一层作为自定义组件，方便写一些公共的业务逻辑，就是因为嵌套了一层才导致我最初使用的方法有性能问题和不能准确限制最大值的问题</p>
            <p>而且使用的是数字，所以设置<code>type=&#39;digit&#39;</code> <em>Tips: digit 类型从 2.4.2 版本开始支持</em></p>
            <p>我们先来看第一种方法</p>
            <h1 id="事件传递法"><a href="#事件传递法" class="headerlink" title="事件传递法"></a>事件传递法</h1>
            <blockquote>
              <p>取这个名字的原因是因为所有都是通过事件来完成的，并且是连续的事件。</p>
            </blockquote>
            <h4 id="定义自定义组件"><a href="#定义自定义组件" class="headerlink" title="定义自定义组件"></a>定义自定义组件</h4>
            <p><em>c-input</em></p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;van-field</span><br><span class="line">    label&#x3D;&quot;&quot;</span><br><span class="line">    :value&#x3D;&quot;value&quot;</span><br><span class="line">    type&#x3D;&quot;digit&quot;</span><br><span class="line">    @input&#x3D;&quot;inputHandler&quot;</span><br><span class="line">    &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;template&gt;</span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: &#39;c-input&#39;,</span><br><span class="line">  props: &#123;</span><br><span class="line">    value: &#123;</span><br><span class="line">      default: &#39;&#39;,</span><br><span class="line">      type: [Number, String],</span><br><span class="line">    &#125;,</span><br><span class="line">    max: &#123;</span><br><span class="line">      default: 0,</span><br><span class="line">      type: [Number, String],</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    inputHandler (value) &#123;</span><br><span class="line">      value &#x3D; this.max &gt; 0 ? Math.min(value, this.max || 0) : value</span><br><span class="line">      this.$emit(&#39;input&#39;, value)</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;&#x2F;script&gt;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h4 id="使用自定义组件"><a href="#使用自定义组件" class="headerlink" title="使用自定义组件"></a>使用自定义组件</h4>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;c-input v-model&#x3D;&quot;inputValue&quot; max&#x3D;&quot;50&quot;&gt;&lt;&#x2F;c-input&gt;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>首先输入1，可以正常显示1；我们再次输入1，这时显示11；我们继续输入1，这时显示50，但是已经能看到我们由111变成50的过程。</p>
            <p>我们继续输入1，这时显示501，而且不会变成50，查看<code>vue-devtools</code>中<code>events</code>的事件都发送成功，<br><img src="" data-original="/images/vue/2530160-b3ba93c227f3c938.webp" alt="image.png"></p>
            <p><img src="" data-original="/images/vue/2530160-692c5182fcab0a4c.webp" alt="image.png"></p>
            <p>只有在输入框失去焦点的时候才能变成50</p>
            <p><img src="" data-original="/images/vue/2530160-9374db8a64d9a137.webp" alt="image.png"></p>
            <h4 id="分析"><a href="#分析" class="headerlink" title="分析"></a>分析</h4>
            <p>想了一下可能是因为自定义组件<code>c-input</code>中的<code>value</code>值始终没有改变，导致<code>van-field</code>中的值不会改变</p>
            <h4 id="尝试一"><a href="#尝试一" class="headerlink" title="尝试一"></a>尝试一</h4>
            <p>既然没有改变，是否可以使用<code>setTimeout</code>，在开始改变的时候先改变值为其它值，然后再改变成我们期望的值。</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">inputHandler (value) &#123;</span><br><span class="line">  value &#x3D; this.max &gt; 0 ? Math.min(value, this.max || 0) : value</span><br><span class="line">  this.$emit(&#39;input&#39;, Date.now())</span><br><span class="line">  setTimeout(() &#x3D;&gt; &#123;</span><br><span class="line">    this.$emit(&#39;input&#39;, value)</span><br><span class="line">  &#125;, 0)</span><br><span class="line">&#125;,</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这种做法会导致事件的死循环，发送第一次<code>input</code>事件会触发<code>vant-field</code>的<code>input</code>事件，然后继续发送第一次<code>input</code>事件，导致死循环</p>
            <p>这时如果修改第一次<code>input</code>事件的值为空字符串，也还是没达到目的。</p>
            <blockquote>
              <p>这里我很想说先发送第一次<code>input</code>事件，再发送第二次<code>input</code>事件，然后就开始死循环，也许是我没有深入研究，结果就是每次触发<code>vant-field</code>组件<code>input</code>事件的值都是第一次<code>input</code>事件的值。有知道了麻烦在评论区回复一下</p>
            </blockquote>
            <h4 id="尝试二"><a href="#尝试二" class="headerlink" title="尝试二"></a>尝试二</h4>
            <p>尝试在computed中增加一个model，作为<code>vant-field</code>的<code>v-model</code>，同时去掉组件上<code>:value</code>数据和<code>input</code>事件监听</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">model: &#123;</span><br><span class="line">  get () &#123;</span><br><span class="line">    return this.value</span><br><span class="line">  &#125;,</span><br><span class="line">  set (val) &#123;</span><br><span class="line">    this.inputHandler(val)</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;,</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>其实效果和尝试一是一样的</p>
            <p>思来想去只能使用最后一个方法，解耦事件（当然代码要多写一点点，也就是一点点而已）</p>
            <h1 id="解耦事件法"><a href="#解耦事件法" class="headerlink" title="解耦事件法"></a>解耦事件法</h1>
            <p>在<code>c-input</code>组件内定一个<code>data</code>数据叫<code>testValue</code>（这个变量在自定义组件外部是看不到的），同时<code>vant-field</code>增加<code>v-model=&#39;testValue&#39;</code>并去掉<code>:value</code>属性</p>
            <p>还是要继续监听<code>vant-field</code>的input事件，在事件处理函数中将处理好的数据赋值给<code>testValue</code>（这时<code>vant-field</code>的值的变化是肉眼看不到的），还是要继续发送input事件，使<code>c-input</code>组件使用者知道自定义组件内部值是多少。</p>
            <p>但是还有个问题，如果组件外部值变化，<code>c-input</code>组件内部不知道值的变化，这时就需要监听<code>value</code>了然后赋值给<code>testValue</code></p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">watch: &#123;</span><br><span class="line">  value (newVal) &#123;</span><br><span class="line">    this.testValue &#x3D; newVal</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;,</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>
            <p>同时如果创建创建的时候有初始值也需要赋值操作</p>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">created () &#123;</span><br><span class="line">  this.testValue &#x3D; this.value</span><br><span class="line">&#125;,</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>运行效果杠杠的，而且当连续按住键盘不放的时候不会出现卡顿的现象。</p>
            <blockquote>
              <p>这个处理逻辑最主要的是把<code>:value=&quot;value&quot;</code> 变成了<code>v-model=&quot;textValue&quot;</code>，把组件值的改变由事件传递解耦，变成了各个组件各自内部的逻辑，减少了相互的依赖。</p>
            </blockquote>
            <p>其实还是那四个字，单一原则</p>
            <h1 id="完整代码"><a href="#完整代码" class="headerlink" title="完整代码"></a>完整代码</h1>
            <figure class="highlight plain">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line">&lt;template&gt;</span><br><span class="line">  &lt;van-field</span><br><span class="line">    label&#x3D;&quot;&quot;</span><br><span class="line">    v-model&#x3D;&quot;testValue&quot;</span><br><span class="line">    type&#x3D;&quot;digit&quot;</span><br><span class="line">    @input&#x3D;&quot;inputHandler&quot;</span><br><span class="line">    &#x2F;&gt;</span><br><span class="line">&lt;&#x2F;template&gt;</span><br><span class="line"></span><br><span class="line">&lt;script&gt;</span><br><span class="line">export default &#123;</span><br><span class="line">  name: &#39;c-input&#39;,</span><br><span class="line">  props: &#123;</span><br><span class="line">    value: &#123;</span><br><span class="line">      default: &#39;&#39;,</span><br><span class="line">      type: [Number, String],</span><br><span class="line">    &#125;,</span><br><span class="line">    max: &#123;</span><br><span class="line">      default: 0,</span><br><span class="line">      type: [Number, String],</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  data () &#123;</span><br><span class="line">    return &#123;</span><br><span class="line">      testValue: &#39;&#39;,</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;,</span><br><span class="line">  watch: &#123;</span><br><span class="line">    value (newVal) &#123;</span><br><span class="line">      this.testValue &#x3D; newVal</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">  created () &#123;</span><br><span class="line">    this.testValue &#x3D; this.value</span><br><span class="line">  &#125;,</span><br><span class="line">  methods: &#123;</span><br><span class="line">    inputHandler (value) &#123;</span><br><span class="line">      value &#x3D; this.max &gt; 0 ? Math.min(value, this.max || 0) : value</span><br><span class="line">      this.testValue &#x3D; value</span><br><span class="line">      this.$emit(&#39;input&#39;, value)</span><br><span class="line">    &#125;,</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;</span><br><span class="line">&lt;&#x2F;script&gt;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>看到这里有人可能会问最后发送了<code>input</code>事件，必然会触发<code>value</code>的<code>watch</code>，导致给<code>textValue</code>赋值，最后还是会触发<code>vant-field</code>的<code>input</code>事件，导致死循环。</p>
            <p>其实是不会的，触发<code>value</code>的<code>watch</code>后赋值的<code>value</code>和<code>textValue</code>是相同的，不会触发<code>vant-field</code>的<code>input</code>事件导致死循环。@</p>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/Vue/" rel="tag"># Vue</a>
              <a href="/tags/van-field/" rel="tag"># van-field</a>
              <a href="/tags/%E7%BB%84%E4%BB%B6/" rel="tag"># 组件</a>
              <a href="/tags/%E6%9C%80%E5%A4%A7%E5%80%BC/" rel="tag"># 最大值</a>
              <a href="/tags/%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BB%84%E4%BB%B6/" rel="tag"># 自定义组件</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2020-07-03-use-of-wechat-applet-plug-in/" rel="prev" title="微信小程序插件使用">
                  <i class="fa fa-chevron-left"></i> 微信小程序插件使用
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2020-07-16-element-type-is-invalid-expected-a-string-for-built-in-components-or/" rel="next" title="Element type is invalid expected a string for built-in components or">
                  Element type is invalid expected a string for built-in components or <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>